<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Infografia extends MY_Controller {

  /**
   * Evita la validacion (enfocado cuando se usa ajax). Ver mas en privilegios_model
   * @var unknown_type
   */
  private $excepcion_privilegio = array('ajax_get_siguiente_numero');

  public function _remap($method){
    $this->carabiner->css(array(
        array('bootstrap/bootstrap-simplex.css', 'screen'),
        array('bootstrap/bootstrap-responsive.css', 'screen'),
        array('bootstrap/charisma-app.css', 'screen'),
        array('bootstrap/jquery-ui-1.8.21.custom.css', 'screen'),
        array('bootstrap/fullcalendar.css', 'screen'),
        array('bootstrap/fullcalendar.print.css', 'print'),
        array('bootstrap/chosen.css', 'screen'),
        array('bootstrap/uniform.default.css', 'screen'),
        array('bootstrap/colorbox.css', 'screen'),
        array('bootstrap/jquery.cleditor.css', 'screen'),
        array('bootstrap/jquery.noty.css', 'screen'),
        array('bootstrap/noty_theme_default.css', 'screen'),
        array('bootstrap/elfinder.min.css', 'screen'),
        array('bootstrap/elfinder.theme.css', 'screen'),
        array('bootstrap/jquery.iphone.toggle.css', 'screen'),
        array('bootstrap/opa-icons.css', 'screen'),
        array('bootstrap/uploadify.css', 'screen'),

        array('base-panel.css', 'screen')
    ));
    $this->carabiner->js(array(
        array('bootstrap/jquery-1.7.2.min.js'),
        array('bootstrap/jquery-ui-1.8.21.custom.min.js'),
        array('bootstrap/bootstrap-transition.js'),
        array('bootstrap/bootstrap-alert.js'),
        array('bootstrap/bootstrap-modal.js'),
        array('bootstrap/bootstrap-dropdown.js'),
        array('bootstrap/bootstrap-scrollspy.js'),
        array('bootstrap/bootstrap-tab.js'),
        array('bootstrap/bootstrap-tooltip.js'),
        array('bootstrap/bootstrap-popover.js'),
        array('bootstrap/bootstrap-button.js'),
        array('bootstrap/bootstrap-collapse.js'),
        array('bootstrap/bootstrap-carousel.js'),
        array('bootstrap/bootstrap-typeahead.js'),
        array('bootstrap/bootstrap-tour.js'),
        array('bootstrap/jquery.cookie.js'),
        array('bootstrap/fullcalendar.min.js'),
        array('bootstrap/jquery.dataTables.min.js'),
        /** chart libraries **/
        array('bootstrap/excanvas.js'),
        array('bootstrap/jquery.flot.min.js'),
        array('bootstrap/jquery.flot.pie.min.js'),
        array('bootstrap/jquery.flot.stack.js'),
        array('bootstrap/jquery.flot.resize.min.js'),

        array('bootstrap/jquery.chosen.min.js'),
        array('bootstrap/jquery.uniform.min.js'),
        array('bootstrap/jquery.colorbox.min.js'),
        array('bootstrap/jquery.cleditor.min.js'),
        array('bootstrap/jquery.noty.js'),
        array('bootstrap/jquery.elfinder.min.js'),
        array('bootstrap/jquery.raty.min.js'),
        array('bootstrap/jquery.iphone.toggle.js'),
        array('bootstrap/jquery.autogrow-textarea.js'),
        array('bootstrap/jquery.uploadify-3.1.min.js'),
        array('bootstrap/jquery.history.js'),
        array('bootstrap/charisma.js'),
    ));

    $this->load->model("empleados_model");
    if($this->empleados_model->checkSession()){
      // $this->empleados_model->excepcion_privilegio = $this->excepcion_privilegio;
      // $this->info_empleado = $this->empleados_model->getInfoEmpleado($_SESSION['id_empleado'], true);
      $this->{$method}();
    }else
      redirect(base_url('panel/home/'));
  }

  public function index()
  {
    $this->carabiner->js(array(
      array('general/msgbox.js'),
      array('panel/infografia/admin.js')
    ));

    $params['seo'] = array(
      'titulo' => 'Administración de artículos'
    );

    $sql_res = $this->db->select("id_tipo, nombre")
                        ->from("articulos_tipo")
                        ->order_by("nombre ASC")
                        ->get();
    $params['tipos_articulos'] = $sql_res->result();

    $this->load->model('infografia_model');
    $params['imagenes'] = $this->infografia_model->get_imagenes();

    if (isset($_GET['msg']))
      $params['frm_errors'] = $this->showMsgs($_GET['msg']);

    $this->load->view('panel/header', $params);
    $this->load->view('panel/general/menu', $params);
    $this->load->view('panel/infografia/admin', $params);
    $this->load->view('panel/footer');
  }

  /**
   * Agrega imagenes a un articulo
   */
  public function agregar()
  {
    $this->carabiner->css(array(
      array('panel/infografia.css', 'screen')
    ));

    $this->carabiner->js(array(
      array('libs/jquery.form.js'),
      array('panel/infografia/infografia.js')
    ));

    $params['seo'] = array(
      'titulo' => 'Agregar Infografía'
    );
    $params['opcmenu_active'] = 'Infografía'; //activa la opcion del menu

    $this->config_add_infografia();
    if ($this->form_validation->run() == FALSE)
    {
      $params['frm_errors'] = $this->showMsgs(2, preg_replace("[\n|\r|\n\r]", '', validation_errors()));
    }
    else
    {
      $this->load->model('infografia_model');
      $res_mdl = $this->infografia_model->agrega_infografia();

      if($res_mdl)
        redirect(base_url('panel/infografia/agregar/?'.String::getVarsLink(array('msg')).'&msg=3'));
    }

    if (isset($_GET['msg']))
      $params['frm_errors'] = $this->showMsgs($_GET['msg']);

    $this->load->view('panel/header', $params);
    $this->load->view('panel/general/menu', $params);
    $this->load->view('panel/infografia/agregar', $params);
    $this->load->view('panel/footer');
  }

  public function config_add_infografia()
  {
    $this->load->library('form_validation');

    $rules = array(
              array('field' => 'fid',
                    'label' => 'Artículo',
                    'rules' => ''),
              array('field' => 'farticulo',
                    'label' => '',
                    'rules' => ''),
              array('field' => 'fnombre_a',
                  'label' => '',
                  'rules' => ''),
              array('field' => 'fpath[]',
                  'label' => 'Imagenes',
                  'rules' => 'required')
            );

    if (isset($_POST['fpath'])) {
      $rules[] = array('field'=>'ftitulo[]', 'label'=>'Título', 'rules'=>'required|max_lenght[200]');
      $rules[] = array('field'=>'ftags[]', 'label'=>'Tags', 'rules'=>'max_lenght[150]');
    }

    $this->form_validation->set_rules($rules);
  }

  public function upload()
  {
    $this->load->library('my_upload');
    $this->load->model('articulos_model');

    ini_set('memory_limit', '64M');

    $path_imgs = 'images/';
    $path = 'infografia/';

    $path_anio = $this->articulos_model->validaDir('anio', $path_imgs, $path);
    $path_mes = $this->articulos_model->validaDir('mes', $path_imgs, $path.$path_anio.'/');

    $config_upload = array(
       'upload_path'     => APPPATH.$path_imgs.'articulos/'.$path.$path_anio.'/'.$path_mes,
       'allowed_types'   => '*',
       'max_size'        => '2048',
       'encrypt_name'    => TRUE
     );

   $config_resize = array(
       'image_library' => 'gd2',
       'source_image'  => '',
       'new_image'     => '',
       'width'         => '400',
       'height'        => '400',
       'maintain_ratio' => TRUE
     );

    $this->my_upload->initialize($config_upload);

    $this->my_upload->do_resize = TRUE;
    $this->my_upload->new_image_path = APPPATH.$path_imgs.'articulos/'.$path.'thumbs/';

    $this->my_upload->config_resize = $config_resize;
    $data = $this->my_upload->do_multiple_array_upload('fimagenes');

    $data_imgs = array();
    foreach ($data as $key => $img) {
      $data_imgs[$key]['path'] = $img['full_path'];

      $a = explode('/', $img['full_path']);
      $b = explode('.', $a[count($a)-1]);
      $data_imgs[$key]['thumb'] = APPPATH.$path_imgs.'articulos/'.$path.'thumbs/'.$b[0].'_thumb.'.$b[1];
    }

    // if (isset($data_img['full_path']))
    // {
      echo json_encode(array('status'=>1, 'resp'=>$data_imgs));
    // }
    // else
    // {
    //   echo json_encode(array('status'=>0, 'resp'=>'Error: El peso de la imagen seleccionada es mayor al permitido.'));
    // }
  }

  public function eliminar()
  {
    if (isset($_GET['id']{0})) {
      $this->load->model('infografia_model');
      $mdl_res = $this->infografia_model->delete_infografia();

      redirect(base_url('panel/infografia/?'.String::getVarsLink(array('id'))).'&msg=4');
    }
  }

  public function ajax_delete()
  {
    $this->load->model('infografia_model');
    $mdl_res = $this->infografia_model->delete_infografia();

    echo json_encode(array('status'=>$mdl_res));
  }

  public function ajax_get_articulos()
  {
    $this->load->model('articulos_model');
    $mdl_res = $this->articulos_model->get_articulos_ajax();

    echo json_encode($mdl_res);
  }

  public function facebook()
  {
    if (isset($_GET['ida']{0}) || isset($_GET['idi']{0}))
    {

      $this->load->model('infografia_model');

      $data = isset($_GET['ida']) ? array('ida' => $_GET['ida']) : array('idi' => urldecode(urldecode($_GET['idi'])));
      $id_publicacion = $this->infografia_model->publica_facebook($data);

      if ($id_publicacion)
        redirect(base_url('panel/infografia/agregar/?'.String::getVarsLink(array('msg')).'&msg=3'));
    }
  }

  /**
   * Muestra mensajes cuando se realiza alguna accion
   * @param unknown_type $tipo
   * @param unknown_type $msg
   * @param unknown_type $title
   */
  private function showMsgs($tipo, $msg='', $title='Articulos')
  {
    switch($tipo){
      case 1:
        $txt = 'El campo ID es requerido.';
        $icono = 'error';
        break;
      case 2: //Cuendo se valida con form_validation
        $txt = $msg;
        $icono = 'error';
        break;
      case 3:
        $txt = 'Imagenes agregadas correctamente.';
        $icono = 'success';
        break;
      case 4:
        $txt = 'La imagen y su información se elimino correctamente.';
        $icono = 'success';
        break;
    }

    return array(
        'title' => $title,
        'msg' => $txt,
        'ico' => $icono);
  }



}

/* End of file infografia.php */
/* Location: ./application/controllers/panel/infografia.php */
